package com.project.dao.Impl;

import com.project.bean.UserBean;
import com.project.dao.IUserDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDate;

@Repository
public class UserDaoImpl extends BaseDao implements IUserDao {
    @Override
    public UserBean login(String name, String pwd) {
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT * FROM t_user WHERE u_name=? AND u_pwd=? ");
            ps.setObject(1,name);
            ps.setObject(2,pwd);
            rs=ps.executeQuery();
            if (rs.next()){
               return this.getUser();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }

        return null;
    }

    private UserBean getUser() {
        UserBean userBean = new UserBean();
        try {
            userBean.setId(rs.getInt("pk_userId"));
            userBean.setName(rs.getString("u_name"));
            userBean.setPwd(rs.getString("u_pwd"));
            userBean.setEmail(rs.getString("u_email"));
            userBean.setImgPath(rs.getString("u_faceImg"));
            userBean.setDate(LocalDate.parse(rs.getString("u_date")));
            userBean.setNickname(rs.getString("u_nickName"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return userBean;
    }

    @Override
    public void sigIn(UserBean userBean) {
        this.setConnection();
        try {
            ps=con.prepareStatement("INSERT INTO t_user(u_name,u_pwd,u_email,u_faceImg,u_nickName,u_date)\n" +
                    "VALUES(?,?,?,?,?,?)");
            ps.setObject(1,userBean.getName());
            ps.setObject(2,userBean.getPwd());
            ps.setObject(3,userBean.getEmail());
            ps.setObject(4,userBean.getImgPath());
            ps.setObject(5,userBean.getNickname());
            ps.setObject(6,userBean.getDate());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
    }

    @Override
    public UserBean findById(Integer id) {
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT * FROM t_user WHERE pk_userId=?");
            ps.setObject(1,id);
            rs=ps.executeQuery();
            if (rs.next()){
                UserBean userBean = new UserBean();
                userBean.setName(rs.getString("u_name"));
                return userBean;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
